package org.brisling.domain.common;

import java.util.HashSet;
import java.util.Set;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.FetchType;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.MappedSuperclass;
import javax.persistence.OneToMany;
import javax.persistence.Transient;

import org.brisling.domain.sysman.inf.HierachicalBeanDataModeler;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;

@MappedSuperclass
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
@JsonIgnoreProperties(value={"hibernateLazyInitializer","handler"})
public class BaseTreeDomain<T extends HierachicalBeanDataModeler<T>> extends BaseDomain implements HierachicalBeanDataModeler<T> {
	
	@Transient
	@JsonIgnore
	private Class<T> clazz = null;	
	
	public BaseTreeDomain(){};
	
	public BaseTreeDomain(Class<T> _clazz){
		this.clazz = _clazz;
	};
	
	
	@ManyToOne(cascade={CascadeType.REFRESH},fetch = FetchType.LAZY)
    @JoinColumn(name="parentid")
	@JsonIgnore
	private T parent;
	
	@Column(name="parentid",insertable=false,updatable=false)
	private Long parentid;
	
	@JsonIgnore
	@OneToMany(mappedBy = "parent",cascade = {CascadeType.ALL},fetch = FetchType.LAZY)
	private Set<T> childrens = new HashSet<T>(0);
	
	@Transient
	private String state="closed";
	
	@JsonIgnore
	public Set<T> getChildrens() {
		return childrens;
	}

	@JsonIgnore
	public void setChildrens(Set<T> childrens) {
		this.childrens = childrens;
	}

	@Override
	public Long getParentid() {
		// TODO Auto-generated method stub
		return this.parentid;
	}

	@Override
	public void setParentid(Long _id) {
		// TODO Auto-generated method stub
		
			if(_id!=null){
				if(parent==null){
					try {
						parent = clazz.newInstance();						
					} catch (InstantiationException | IllegalAccessException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
				
				parent.setId(_id);
				this.parentid = _id;
			}
		
	}

	@Override
	public String getState() {
		// TODO Auto-generated method stub
		return this.state;
	}

	@Override
	public void setState(String _state) {
		// TODO Auto-generated method stub
		this.state = _state;
	}

	@Override
	public String getText() {
		// TODO Auto-generated method stub
		return this.getName();
	}

	@Override
	public String toTreeString() {
		// TODO Auto-generated method stub
		return null;
	}

	@JsonIgnore
	public Class<T> getClazz() {
		return clazz;
	}

	@JsonIgnore
	public void setClazz(Class<T> clazz) {
		this.clazz = clazz;
	}

	@JsonIgnore
	public T getParent() {
		return parent;
	}

	@JsonIgnore
	public void setParent(T parent) {
		this.parent = parent;
	}
	
	
	
}
